package com.fowo.api.datainterface.service.impl.implCore;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazon.spapi.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.AWSAuthenticationCredentialsProvider;
import com.amazon.spapi.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.RateLimitConfiguration;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.model.DataContextModel;
import com.fowo.api.datainterface.service.serviceCore.BaseFromService;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.datainterface.util.amazon.AmazonApi;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
@Slf4j
@DS("ds24")
@RequiredArgsConstructor
public class AmazonServiceImpl  implements BaseFromService {
    @Resource
    private Common common;

    @Override
    public DataTypeKind getType() {
        return DataTypeKind.Amazon;
    }

    @SneakyThrows
    @Override
    public Object invokeFrom(DataContextModel.DatainterfaceFromModel from, JSONObject currentParamsMap, JSONObject currentHeadersMap) {
        DataContextModel.DatainterfaceAuthorityModel datainterfaceAuthority = from.getAuthority();
        Assert.isTrue(ObjectUtil.isAllNotEmpty(datainterfaceAuthority), "{} 来源接口 {} 金蝶拓展授权信息配置错误，请检查配置", StrUtil.concat(true, from.getTaskCode()), from.getEnCode());
        String basePath = datainterfaceAuthority.getRootPath();

        String userAccessKeyId = common.getAuthoritySimpleFactory(datainterfaceAuthority, "userAccessKeyId");
        String userSecretKey = common.getAuthoritySimpleFactory(datainterfaceAuthority, "userSecretKey");
        String roleArn = common.getAuthoritySimpleFactory(datainterfaceAuthority, "roleArn");
        String clientId = common.getAuthoritySimpleFactory(datainterfaceAuthority, "clientId");
        String clientSecret = common.getAuthoritySimpleFactory(datainterfaceAuthority, "clientSecret");
        String refreshToken = common.getAuthoritySimpleFactory(datainterfaceAuthority, "refreshToken");
        String endpoint = common.getAuthoritySimpleFactory(datainterfaceAuthority, "endpoint");
        String region = common.getAuthoritySimpleFactory(datainterfaceAuthority, "region");
        Assert.isTrue(ObjectUtil.isAllNotEmpty(userAccessKeyId, userSecretKey, region, roleArn, clientId, clientSecret, refreshToken, endpoint), "{} 来源接口 {} 请配置授权格式,例: {\"userAccessKeyId\":\"\",\"userSecretKey\":\"\",\"region\":\"\",\"roleArn\":\"\",\"clientId\":\"\",\"clientSecret\":\"\",\"refreshToken\":\"\",\"endpoint\":\"\"}", StrUtil.concat(true, from.getTaskCode()), from.getEnCode());
        AWSAuthenticationCredentials awsAuthenticationCredentials=AWSAuthenticationCredentials.builder()
                //IAM user的accessKeyId
                .accessKeyId(userAccessKeyId)
                //IAM user的secretKey
                .secretKey(userSecretKey)
                //这里按照amazon对不同region的分区填写
                .region(region)
                .build();
        AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider=AWSAuthenticationCredentialsProvider.builder()
                //IAM role，特别注意：最好用IAM role当做IAM ARN去申请app
                // 而且IAM user需要添加内联策略STS关联上IAM role，具体操作看：https://www.spapi.org.cn/cn/model2/_2_console.html
                .roleArn(roleArn)
                .roleSessionName(getRandomNonce())
                .build();
        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                //申请app后LWA中的clientId
                .clientId(clientId)
                //申请app后LWA中的clientSecret
                .clientSecret(clientSecret)
                //店铺授权时产生的refreshToken或者app自授权生成的
                .refreshToken(refreshToken)
                .endpoint(endpoint)
                .build();
        RateLimitConfiguration rateLimitConfiguration=new RateLimitConfiguration() {
            @Override
            public Double getRateLimitPermit() {
                return null;
            }

            @Override
            public Long getTimeOut() {
                return null;
            }
        };
        AmazonApi amazonApi = new AmazonApi.Builder()
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                .rateLimitConfigurationOnRequests(rateLimitConfiguration)
                .endpoint(basePath)
                .interfaceUrl(from.getInterfaceUrl())
                .requestMethod(from.getRequestMethod())
                .build();
        return amazonApi.getHttpInfo();
    }
    private String getRandomNonce() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
